﻿using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace 自定义配置提供者
{
    internal class MyConfigProvider : FileConfigurationProvider
    {
        public MyConfigProvider(FileConfigurationSource source) : base(source)
        {

        }

        public override void Load(Stream stream)
        {
            //创建一个忽略大小写的字典
            var data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(stream);
            var csNodes = xmlDoc.SelectNodes("/configuration/connectionStrings/add");
            foreach (XmlNode xmlNode in csNodes.Cast<XmlNode>())
            {
                string name = xmlNode.Attributes["name"].Value;
                string connectionString = xmlNode.Attributes["connectionString"].Value;
                var providerName = xmlNode.Attributes["providerName"];

                data[$"{name}:connectionString"] = connectionString;
                
                if (providerName != null)
                {
                    data[$"{name}:providerName"] = providerName.Value;
                }
            }

            //appsettings
            var asNodes = xmlDoc.SelectNodes("/configuration/appSettings/add");
            foreach (XmlNode xmlNode in asNodes.Cast<XmlNode>())
            {
                string key = xmlNode.Attributes["key"].Value;
                key = key.Replace('.', ':');
                string value = xmlNode.Attributes["value"].Value;
                data[key] = value;
            }

            this.Data = data;
        }
    }
}
